const Actions = require('./actions');
const DB = require('app/db');
import { NEW, RUNNING, TERMINATED, COMPLETED, CANCELED } from 'clientConfig/constants'
import { monStorage, Storage } from 'clientConfig/util/StoreData';
import { guid, getTime, getMarkdownText,sendNotice} from 'clientConfig/util/queryurlfield';
const { Toast } = SaltUI;
import { Control } from 'react-keeper';
let upfileName = []

module.exports = Reflux.createStore({
    listenables: [Actions],
    data: {
        
    },
    onFetch: function (params, cb) {
        let t = this;
        upfileName = [];
        DB.Approval.get_approval_list({
            module_type: "tender",
            status: COMPLETED,
            proj_category:"tenderplan",
            PageNum: 0,
            CountForAPage: 30
        })
            .then((content) => {
                var proNumAll = [];
                var proNameAll = [];
                if (content.list instanceof Array) {
                    var obj = {};
                    content.list.map((item, index) => {
                        obj.value = index;
                        obj.text = item.proj_name;
                        obj.proj_category = item.proj_category;
                        obj.proj_webhook = item.proj_webhook;
                        obj.process_id = item.process_id;
                        obj.folder_id = item.folder_id;
                        proNameAll.push(obj);
                        proNumAll.push(item.proj_num);
                        obj = {};
                    })
                }          
                t.data.proNumAll = proNumAll
                t.data.proNameAll = proNameAll
                t.data.upfileName = []
                t.updateComponent()
            })
            .catch(function (error) {

            });
    },
    onSubmit: function (params, cb) {
        let t = this;
        let data = this.fit(params);
        if (params.pagedata) {
            data = this.modify(data, params);
        }
        DB.Approval.send_approval(data)
            .then((content) => {
                Toast.show({
                    type: 'success',
                    content: params.edit ? '你的变更申请已提交' : '你的成果申请已提交'
                });
                Control.go(-1)
                t.updateApproval(params.process_id, data);
                let notice_info = {
                    "process_id": data.process_id,
                    "proj_num": data.proj_num,
                    "proj_name": data.proj_name,
                    "create_time": data.create_time,
                    "status": data.status,
                    "type": params.pagedata?"变更申请":"待我审批的"
                }
                sendNotice(data.approvers[data.next_cursor], notice_info);
                 
            })
            .catch((error) => {
                cb && cb(t.data);
            });
    },
    fit: function (params) {
        // debugger
        let agent_id = Storage.get('user.agentid');
        let create_time = getTime();
        let finish_time = "";
        let originator_user = monStorage.get('user.nickname');
        let originator_user_id = monStorage.get('user.id') //审批发起人的userid
        let dept_id = monStorage.get('user.department');
        let approvers = params.data.approvers;
        let approvers_id = params.data.approvers_id;
        let cc_list = params.data.copyers;
        let cc_list_id = params.data.cc_list_id;
        var array = [];
        for (let i = 0; i < approvers.length; i++) {
            array.push(JSON.stringify({ content: "", file: "", imgae: "" }));
        }
        let process_result = array.length > 1 ? array : JSON.stringify({ "content": "", "file": "", "imgae": "" });
        let next_cursor = 0;
        const status = NEW;
        const module_type = "achievements";
        const proj_category = "tenderachievement";
        const proj_num = params.data.proNum;
        const proj_name = params.data.proName.text;
        var proj_webhook = "";    
        const proj_markdown = '';
        const process_id = guid();
        let nodelists = [];
        var node_obj = {}
        let node_info = [];
        for (let i = 0; i < params.node.length + 1; i++) {
            if (i < params.node.length) {
                var obj = {}
                obj.name = params.node[i].label;
                obj.value = params.data[params.node[i].name].text ? params.data[params.node[i].name].text : params.data[params.node[i].name];
                if(obj.name.includes("时间")){
                    obj.value = new Date(obj.value).toLocaleDateString()
                }
            } else {
                var obj = {}
                obj.name = "上传附件";
                obj.value = JSON.stringify(this.data.upfileName);
            }
            node_info.push(obj);
        }
        node_obj.node_info = node_info;
        Object.assign(node_obj, { node_name: 'achievements', modified: "0", permission: "1" });
        nodelists.push(node_obj)
        let form_component_values = {
            content: { achievements_name: params.data["achieveName"],process_id:params.process_id},
            nodelists: nodelists
        }
        return Object.assign({}, { agent_id, create_time, finish_time, originator_user, dept_id, approvers, approvers_id, cc_list, cc_list_id, process_result, next_cursor, status, module_type, proj_category, proj_num, proj_name, proj_webhook, process_id, form_component_values, proj_markdown })
    },
    updateComponent: function () {
        this.trigger(this.data);
    },
    updateApproval: function (process_id, data) {
        DB.Approval.get_approval_detail({ process_id })
            .then((content) => {
                let nodelists = content.form_component_values.nodelists;
                let node = data.form_component_values.nodelists[0].node_info[2].value;
                //#warning-成果文档未写
                let achievements = "";
                let time = new Date(data.form_component_values.nodelists[0].node_info[1].value).toLocaleDateString();
                let node_achievements = {
                    "achievements_name": data.form_component_values.content.achievements_name,//成果名称
                    "time": time,//成果完成时间
                    "status": data.status,//成果状态0，1，2//整型，
                    "achievements": achievements,//成果文档
                    "process_id":data.process_id//审批单id
                }
                for (let i = 0; i < nodelists.length; i++) {
                    if (nodelists[i].node_name.includes(node)) {
                        nodelists[i].node_achievements.push(node_achievements);
                    }
                }
                let updataContent = {
                    "form_component_values": {
                        nodelists
                    }
                }
                DB.Approval.update_approval.config.query = { process_id: process_id }
                DB.Approval.update_approval(updataContent).then((content) => {// 成功
                    //    debugger

                })
            })
            .catch((error) => {
                cb && cb(t.data);
            });



    },
    modify: function (new_data, old_data) {
        let edit = old_data.edit;
        old_data = old_data.pagedata;
        new_data.proj_category = "changereq";
        let old_change = [];//变更前字段 发送群消息
        let new_change = [];//变更后字段 发送群消息
        let form_component_values_new = new_data.form_component_values;
        let nodelists_new = form_component_values_new.nodelists;
        for (let i = 0; i < nodelists_new.length; i++) {
            let node_info_new = nodelists_new[i].node_info;
            let node_info_old = old_data.node_info;
            for (let j = 0; j < node_info_new.length; j++) {
                if (node_info_new[j].value != node_info_old[j].value) {
                    node_info_new[j].ext_value = node_info_old[j].value//变更过
                    old_change.push(node_info_old[j].value);
                    new_change.push(node_info_new[j].value);
                }
            }
        }
        form_component_values_new.nodelists = nodelists_new;
        form_component_values_new.content.changerecord_type = JSON.stringify({
            type: edit ? "撤销申请" : "内容变更",
            old_process_id: old_data.process_id
        })
        new_data.form_component_values = form_component_values_new;
        let { create_time, originator_user, approvers, approvers_id, next_cursor, proj_name, proj_num, status } = { ...new_data };
        const proj_markdown = getMarkdownText({ old_change, new_change, change_type: edit ? "撤销申请" : "内容变更", create_time, originator_user, approvers: approvers[next_cursor], proj_name, proj_num, status }, "change")
        new_data.proj_markdown = proj_markdown;
        return new_data;
    },
    onUpFiles: function (params, data, ele) {
        // debugger
        let t = this;
        ele.style.opacity = 1;
        ele.style.width = "50%";
        fetch("/its/upload_file?proj_name=" + params.name +"&file_uper="+Storage.get("user.id")+ "&file_uper_name=" + monStorage.get('user.nickname') +"&folder_id="+params.folder_id+ "&file_version=" + params.version, {
            method: "POST",
            body: data
        }).then(function (response) {
            return response.json();
        }).then(function (result) {
            ele.style.width = "100%"
            setTimeout(function () {
                ele.style.opacity = 0
            }, 700);
            setTimeout(function () {
                ele.style.width = 0
            }, 1000);
            upfileName.push({ fileName: result.content.file_name, fileId: result.content.file_id, file_version: result.content.file_version })
            t.data.upfileName = upfileName
            t.updateComponent()
        }, function (error) {

        })
    },
    onDelFiles: function (id) {
        let t = this
        DB.File.delete_file({
            file_id: id,
            id:Storage.get('user.id')
        })
            .then((content) => { // 成功
                for (var i = 0; i < upfileName.length; i++) {
                    if (upfileName[i].fileId == id) {
                        upfileName.splice(i, 1)
                    }
                }
                t.data.upfileName = upfileName
                t.updateComponent()
            })
            .catch((error) => { // 失败 or 有异常被捕获

            });
    },
    onFetchFilePaths: function (params, cb) {
        let t = this;
        DB.File.get_filelists({
            folder_id: params.folder_id,
            id:Storage.get('user.id'),
            type: 1
        })
            .then((content) => {
                content = content.file_list;
                let obj = {};
                let list = [];
                if (content.length > 0) {
                    for (let item of content) {
                        obj.folder = item.file_folder;//是否为文件夹true
                        obj.process_id = item.process_id;//关联的审批单-根目录时含有，其他可省略
                        obj.uploader = item.file_uper;//文件上传者id
                        obj.file_uper_name = item.file_uper_name//文件上传人
                        // obj.folder_name = item.folder_name;//文件夹名称
                        obj.fileName = item.folder_name;//文件夹名称
                        obj.date = item.file_uptime;//文件夹创建时间
                        obj.folder_id = item.folder_id;//文件夹id
                        /*---------------*/
                        obj.fileSize = '---'
                        obj.title=  item.folder_name;
                        obj.imgUrl = "../../../../../../assets/img/checknohook.png"
                        list.push(obj)
                        obj = {};
                    }
                }
                this.data.pathdata = list;
                t.updateComponent();
            })
            .catch((error) => {

            });
    }
});
